package com.qingyun.system.model.query;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.io.Serial;
import java.io.Serializable;
import java.util.Arrays;

/**
 * 基础分页和排序查询类
 */
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class PagingAndSortingQuery implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 页码,默认1
     */
    private Integer pageNo = 1;

    /**
     * 页大小，默认10
     */
    private Integer pageSize;

    /**
     * 排序字段
     */
    private String sortField = "";

    /**
     * 排序方式，true为升序，false为降序，默认false
     */
    private Boolean isAsc = false;

    /**
     * 转换为Mybatis-Plus分页对象
     * @param orderItems 排序项对象
     * @return
     * @param <T>
     */
    public <T> Page<T> toMpPage(OrderItem ... orderItems) {
        Page<T> page =new Page<>(pageNo, pageSize);
        // 是否手动指定多个排序项
        if(orderItems!= null && orderItems.length > 0) {
            Arrays.stream(orderItems).forEach(page::addOrder);
            return page;
        }
        // 前端是否指定排序字段
        else if(StringUtils.hasLength(sortField)) {
            page.addOrder(isAsc ? OrderItem.asc(sortField) : OrderItem.desc(sortField));
            return page;
        }
        else {
            // 默认无排序字段
            return page;
        }
    }

    /**
     * 转换为Mybatis-Plus分页对象
     * @param defaultSortField
     * @param isAsc
     * @return
     * @param <T>
     */
    public <T> Page<T> toMpPage(String defaultSortField, boolean isAsc) {
        if (StringUtils.isEmpty(sortField)){
            sortField = defaultSortField;
            this.isAsc = isAsc;
        }
        Page<T> page = new Page<>(pageNo, pageSize);
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(this.isAsc);
        orderItem.setColumn(sortField);
        page.addOrder(orderItem);
        return page;
    }
}
